﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Primitive.Threading.Sync
{
    class RegisteredWaitHandleDemo
    {
        static AutoResetEvent release_event = new AutoResetEvent(false);
        public static void UnregWaitHandle()
        {
            AutoResetEvent run_lock = new AutoResetEvent(false);
            RegisteredWaitHandle rwh = ThreadPool.RegisterWaitForSingleObject(
          run_lock, 
          EventOperation, 
          null, 
          5000,
          false); 
            run_lock.Set();
            rwh.Unregister(release_event);
            Release();

        }

        private static void Release()
        {
            release_event.WaitOne();
            Console.WriteLine("Clearing...");
        }


        public static void Run()
        {
            AutoResetEvent are = new AutoResetEvent(false);
            RegisteredWaitHandle rwh = ThreadPool.RegisterWaitForSingleObject(
            are, 
            EventOperation,
            null, 
            5000, 
            false); 
            Char operation = (Char)0;
            while (operation != 'Q')
            {
                Console.WriteLine("S=Signal, Q=Quit?");
                operation = Char.ToUpper(Console.ReadKey(true).KeyChar);
                if (operation == 'S') are.Set(); // User want to set the event
            }
            rwh.Unregister(null);
        }
     
        private static void EventOperation(Object state, Boolean timedOut)
        {
            Console.WriteLine(timedOut ? "Timeout" : "Event became true");
        }
    }
}
